import React, { useState, memo, useEffect, useCallback } from 'react';
import { Row, Col, Button } from 'tdesign-react';
import { getAuthLog } from 'api/user';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { createColumns } from 'utils/tableUtils';
import { useNavigate } from 'react-router-dom';
import {
  CHANNEL_PROMOTION_MAP,
  PLATFORM_OPTIONS,
  PROMOTION_MAP,
  USER_TYPE_MAP,
  USER_TYPE_OPTIONS,
} from 'constants/index';
import SakuraSearchForm from 'components/SakuraSearchForm';
import IppeakTable from 'components/IppeakTable';
import { createRequestParams } from 'utils';
// 初始查询参数
const INITIAL_QUERY = {
  page: 1,
  page_size: 10,
};

// 初始表格状态
const INITIAL_TABLE_STATE = {
  list: [],
  total: 0,
  current: 1,
  pageSize: 10,
};

export const SelectTable = () => {
  const navigate = useNavigate();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const { loading, setLoading } = useLoading(false);

  // 表格状态管理
  const [table, setTable] = useState(INITIAL_TABLE_STATE);
  const [query, setQuery] = useState<any>(INITIAL_QUERY);

  const { list, total } = table;

  // 表格列定义
  const columns = createColumns([
    {
      label: '用户ID',
      align: 'left',
      key: 'user_id',
      width: 60,
    },
    {
      label: '邮箱',
      key: 'username',
      width: 120,
    },
    
    {
      label: '用户类型',
      key: 'tags',
      render({ row }: any) {
        const tagColor = row.tags === 'vip' ? '#7868e6' : row.tags === 'staff' ? '#f80' : 'inherit';
        return <span style={{ color: tagColor, cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>;
      },
      width: 100,
    },
    {
      label: '登录时间',
      key: 'ts',
      type: 'date',
    },
    {
      label: '登录ip',
      key: 'last_ip',
    },
    // {
    //   label: '连续登录天数',
    //   key: 'register_time',
    //   type: 'date',
    // },
  ]);

  // 表单字段定义
  const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
      onChange: (value: any) => {
        if (value == null || String(value).trim() === '') {
          setQuery((prev: any) => {
            const { id, ...rest } = prev || {};
            return { ...rest };
          });
        }
      },
      colWrap: {
        colSpan: 2.5,
        labelWidth: 60,
        width: 86,
      },
    },
    {
      label: '邮箱',
      name: 'username_pre',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 50,
        width: 156,
      },
    },
    {
      label: '用户类型',
      name: 'tags',
      type: 'select',
      options: USER_TYPE_OPTIONS,
    },
  ];

  useEffect(() => {
    if (!query.a_source) {
      delete query?.origin;
      delete query?.channel;
      delete query?.source;
      delete query?.channel_name;
      delete query?.series;
    }
  }, [query.a_source]);
  // 统一的字段清除处理函数
  const handleFieldClear = (fieldName: string) => {
    setQuery((prev: any) => {
      const { [fieldName]: removed, ...rest } = prev || {};
      return { ...rest };
    });
  };

  // 获取用户列表数据
  const fetchUserList = useCallback(
    async (params?: any) => {
      setLoading(true);
      try {
        // 合并参数并过滤空值，query 优先级更高
        delete query?.register_time;
        const requestParams = createRequestParams({ ...query, ...params });
        const res: any = await getAuthLog(requestParams);
        setLoading(false);
        setTable((pre: any) => ({
          ...pre,
          list: res.results || [],
          total: res.total || 0,
        }));
      } catch (err) {
        console.log(err, 'err');
        setLoading(false);
      }
    },
    [query],
  );

  // 处理选择变化
  const onSelectChange = useCallback((value: (string | number)[]) => {
    setSelectedRowKeys(value);
  }, []);

  const handleSearch = useCallback((values: any) => {
    let platforms = PLATFORM_OPTIONS.map((item) => item.label);
    let promotions = PROMOTION_MAP.map((item) => item.label); // 推广
    let biddings = CHANNEL_PROMOTION_MAP.map((item) => item.label); // 渠道
    let type = '';
    if (values.a_source == 1 || values.a_source == 2) {
      type = 'origin';
    } else if (promotions.includes(values.a_source)) {
      type = 'source';
      delete values.channel_name;
    } else if (biddings.includes(values.a_source)) {
      type = 'channel';
      delete values.series;
    }
    const startTime = values?.register_time?.[0] || '';
    const endTime = values?.register_time?.[1] || '';
    const query = {
      ...values,
      [type]: values.a_source,
      start_time: startTime,
      end_time: endTime,
    };
    setQuery((pre: any) => ({
      ...query,
      page: 1,
      page_size: 10,
    }));
  }, []);

  const handleReset = () => {
    setQuery((pre: typeof INITIAL_QUERY) => ({
      page: 1,
      page_size: 10,
    }));
  };

  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setQuery((pre: typeof INITIAL_QUERY) => ({
      ...pre,
      page: page,
      page_size: pageSize || 10,
    }));
  }, []);

  // 处理当前页变化
  const handleCurrentChange = useCallback(
    (current: number, pageInfo: any) => {
      console.log('current', current);
      console.log('pageInfo', pageInfo);
      handlePaginationChange(pageInfo.current, query.page_size);
    },
    [query.page_size, handlePaginationChange],
  );

  // 处理每页条数变化
  const handlePageSizeChange = useCallback(
    (size: number) => {
      handlePaginationChange(1, size); // 切换每页条数时重置到第一页
    },
    [handlePaginationChange],
  );

  // 监听查询参数变化，自动获取数据
  useEffect(() => {
    fetchUserList();
  }, [fetchUserList]);

  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm
            fields={formFields}
            onSearch={handleSearch}
            onFieldClear={handleFieldClear}
            onReset={handleReset}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        tableHeight={272}
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: query.page_size,
          total,
          current: query.page,
          showJumper: true,
          onCurrentChange: handleCurrentChange,
          onPageSizeChange: handlePageSizeChange,
        }}
      />
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
